package linc.cool.framework.protocol.http;

import com.alibaba.fastjson.JSONObject;
import linc.cool.framework.Invocation;
import linc.cool.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author yqlin
 * @date 2022/3/11 4:20 上午
 * @description
 */
public class HttpServerHandler {
    public void handler(HttpServletRequest req, HttpServletResponse resp) {
        // 处理请求的逻辑
        try {
            Invocation invocation = JSONObject.parseObject(req.getInputStream(), Invocation.class);
            System.out.println("invocation:" + invocation);
            var interfaceName = invocation.getInterfaceName();
            var implClass = LocalRegister.get(interfaceName);
            if (Objects.isNull(implClass)) {
                throw new RuntimeException("service not registered");
            }
            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            var result = (String) method.invoke(implClass.getDeclaredConstructor().newInstance(), invocation.getParams());
            System.out.println("tomcat:" + result);
            // 将结果返回
            IOUtils.write(result, resp.getOutputStream());
        } catch (IOException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
